package com.message.queue.rocket.defaultmq;

import com.message.queue.constant.RocketConstant;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.remoting.common.RemotingHelper;

import java.util.List;

/**
 * Created by 张波 on 2019/9/22.
 */
@Slf4j
public class DefaultConsumer {

    public static void main(String[] args) throws MQClientException {
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("default_consumer");
        consumer.setNamesrvAddr(RocketConstant.NAME_SERVER);
        consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_LAST_OFFSET);
        consumer.subscribe("test_quick_topic", "*");

        consumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
                MessageExt messageExt = msgs.get(0);
                try {
                    String body = new String(messageExt.getBody(), RemotingHelper.DEFAULT_CHARSET);
                    System.out.println("topic:" + messageExt.getTopic() + ",tags:" + messageExt.getTags() + ",keys:" + messageExt.getKeys()
                            + ",body:" + body);
//                    if("key0".equals(messageExt.getKeys())) {
//                        //TODO 手动异常，触发补偿重试机制
//                        int i = 1 / 0;
//                        System.out.println(i);
//                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    System.out.println("reconsumetimes:" + messageExt.getReconsumeTimes());
                    if(messageExt.getReconsumeTimes() >= 3) {
                        //TODO  已经重试3次了，不再做处理了，在此处记录日志做补偿机制，返回成功
                        log.error("message:" + messageExt.getKeys());
                        return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                    }
                    return ConsumeConcurrentlyStatus.RECONSUME_LATER;
                }
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });
        consumer.start();
    }
}
